const express = require('express')
const mongoose = require('mongoose')

//链接mongo,并且使用recruit这个集合
const DB_URL = 'mongodb://localhost:27017/recruit'
mongoose.connect(DB_URL)
mongoose.connection.on('connected', () => {
    console.log('mongo connect success')
})

//类似于mysql的表，mongo里有文档、字段的概念
const User = mongoose.model('user', new mongoose.Schema({
    user: {type: String, require: true},
    age: {type: Number, require: true}
}))

//新增
/*User.create({
    user: '我媳妇：小瓶瓶',
    age: 18
}, (err, doc) => {
    if (!err) {
        console.log(doc)
    } else {
        console.log(err)
    }
})*/
//删除
/*User.remove({age: 18}, (err, doc) => {
    if (!err) {
        console.log(doc)
    } else {
        console.log(err)
    }
})*/
//修改
/*User.update({'user': '王凯令'}, {
    '$set': {age: 23}
}, (err, doc) => {
    if (!err) {
        console.log(doc)
    } else {
        console.log(err)
    }
})*/

const app = express()

app.get('/', (req, res) => {
    res.send('<h1>hello world</h1>')
})

app.get('/data', (req, res) => {
    //查询所有
    User.find({}, (err, doc) => {
        res.json(doc)
    })
    //查找一条
    /*User.findOne({user: '王凯令'}, (err, doc) => {
        res.json(doc)
    })*/
})


app.listen(8080, () => {
    console.log('Node app start at port 8080')
})